<template>
  <div class="search-list">
    <!-- v-el-table-infinite-scroll="loadMore" 无限滚动 -->
    <el-table ref="searchListTable" v-loading="searchListLoad" :data="musicList" max-height="600" :show-header="false" :empty-text="searchTableEmptyText" @cell-mouse-enter="searchListHover" @cell-mouse-leave="searchListMouseLeave">
      <el-table-column prop="hover" min-width="40">
        <template slot-scope="scope">
          <i v-show="scope.row.hover" class="el-icon-plus btn" @click="Add2MusicList(scope.row)" title="添加到播放列表"></i>
          <!-- <i v-show="scope.row.hover" class="el-icon-video-play btn" @click="playMusic(scope.row)" title="播放"></i> -->
          <!-- <i v-show="scope.row.hover" class="el-icon-star-off btn" @click="collectMusic(scope.row)" title="收藏"></i> -->
        </template>
      </el-table-column>
      <el-table-column prop="title" label="歌曲" min-width="125" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column prop="artist" label="歌手" width="80" align="right" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column prop="audition" label="完整性" width="50">
        <template slot-scope="scope">
          <img v-if="scope.row.audition === 0" src="../../static/icon/audition.png" alt="" />
          <!-- <span v-if="scope.row.audition === 0">试听</span> -->
        </template>
      </el-table-column>
      <!-- <el-table-column prop="sourceId" label="来源" width="50">
        </el-table-column> -->
      <!-- 加载更多 -->
      <p slot="append" v-if="musicList.length" @click="loadMore" class="load-more">点击加载更多...</p>
    </el-table>
  </div>
</template>

<script>
import { formatLyricsByKuGou, searchFromKuGou, getMusicInfoFromKuGou } from '../api/KuGou'
import { formatLyricsByMiGU, searchFromMiGu, getLyricsFromMiGu } from '../api/MiGu'
import { formatLyricsByQQ, searchFromQQ, getMusicInfoFromQQ, getLyricsFromQQ } from '../api/QQ'
import { formatLyricsByNetease, searchFromNetease, getMusicUrlFromNetease, checkUrlByNetease, getLyricsFromNetease, getAlbumImgFromNetease } from '../api/Netease'
import { searchFromKuWo, getMusicInfoFromKuWo, getMusicUrlFromKuWo } from '../api/KuWo'
import { mapState, mapMutations } from 'vuex'
export default {
  props: {
    searchKey: {
      type: String,
      required: true
    },
    searchType: {
      type: String,
      required: true
    },
    panelShowOrClose: {
      type: Boolean,
      required: true
    }
  },
  computed: {
    ...mapState([
      'playList',
      'currentPlayMusicIndex',
    ])
  },
  watch: {
    page: {
      handler () {
        this.searchMusic()
      },
      immediate: false
    },
    panelShowOrClose: {
      handler () {
        this.musicList = []
      }
    },
    searchType: {
      handler () {
        this.page = 1
        this.searchMusic()
      }
    }
  },
  data () {
    return {
      page: 1,
      pagesize: 20,
      searchTableEmptyText: '搜一下，试试看。',
      musicList: [],
      searchListLoad: false, // 搜索列表懒加载
    }
  },
  methods: {
    ...mapMutations([
      'add2PlayList',
      'updatePlayIndex',
    ]),

    // 搜索列表鼠标划入
    searchListHover (row) {
      row.hover = true
    },

    // 搜索列表鼠标划出
    searchListMouseLeave (row) {
      row.hover = false
    },

    // 播放歌曲
    playMusic (row) {
      this.Add2MusicList(row)
      // console.log(this.currentPlayMusicIndex)
      // console.log(this.playList.length)
      // this.updatePlayIndex(this.playList[this.playList.length + 1])
    },

    // 添加到播放列表
    Add2MusicList (row) {
      // 检查是否已添加过
      if (!!this.checkMusicList(row)) {
        return this.showMessage('该歌曲已在播放列表当中')
      }

      // 分站点添加音乐
      switch (row.sourceId) {
        case 0: // 添加酷狗音乐
          getMusicInfoFromKuGou(row.hash, row.id).then(res => {
            if (res.status !== 200) {
              throw new Error('获取酷狗音乐信息失败')
            }
            // console.log(res.data)
            this.add2PlayList({
              title: res.data.song_name,
              artist: res.data.author_name,
              src: res.data.play_url,
              backup_src: res.data.play_backup_url, // 备用播放地址
              img: res.data.img,
              lyrics: res.data.lyrics, // 未格式化的歌词，播放时再进行格式化
              sourceId: row.sourceId,
              hash: row.hash,
              id: row.id,
              time: new Date().getTime(),
              loved: false,
            })
            return this.showMessage('音乐添加成功')
          })
          break;
        case 1: // 添加咪咕音乐
          getLyricsFromMiGu(row.id).then(res => {
            // console.log(res.data)
            this.add2PlayList({
              title: row.title,
              artist: row.artist,
              src: row.src,
              img: row.img,
              lyrics: res.data.lyric,
              translateLyrics: res.data.translatedLyric,
              sourceId: row.sourceId,
              id: row.id, // 根据id获取歌词
              time: new Date().getTime(),
              loved: false,
            })
            return this.showMessage('音乐添加成功')
          })
          break;
        case 2: // 添加QQ音乐
          // checkURL({ url: row.src }).then(res => {
          //   console.log(row.src)
          //   console.log(res.data.code)
          // }).catch(err => {
          //   console.log(err)
          // })
          // console.log(row.src)
          // console.log(row)
          this.add2PlayList({
            title: row.title,
            artist: row.artist,
            src: row.src, // 播放前需要对QQ音乐的地址进行检查，返回403则不能播放
            img: row.img,
            lyrcis: row.lyrics,
            sourceId: row.sourceId,
            id: row.id, // 根据id获取歌曲信息
            time: new Date().getTime(),
            loved: false,
          })
          return this.showMessage('音乐添加成功')
          break;
        case 3: // 添加网易云音乐
          Promise.all([getLyricsFromNetease(row.id), getMusicUrlFromNetease(row.id), checkUrlByNetease(row.id), getAlbumImgFromNetease(row.albumid)]).then(res => {
            if (!res[2].data.success) this.checkMusicUrl()
            this.add2PlayList({
              title: row.title,
              artist: row.artist,
              src: res[1].data.data[0].url, // 通过id获取歌曲链接
              img: res[3].data.album.picUrl, // 通过专辑id获取歌词封面
              lyrics: !res[0].data.nolyric ? res[0].data.lrc.lyric : '',
              translateLyrics: res[0].data.tlyric.lyric,
              sourceId: row.sourceId,
              id: row.id, // 根据id获取歌曲链接和歌词
              time: new Date().getTime(),
              loved: false,
            })
            return this.showMessage('音乐添加成功')
          })
          break;
        case 4: // 添加酷我音乐
          Promise.all([getMusicInfoFromKuWo(row.id), getMusicUrlFromKuWo(row.id)]).then(res => {
            this.add2PlayList({
              title: row.title,
              artist: row.artist,
              src: res[1].data.url, // 通过id获取歌曲链接
              img: res[0].data.data.albumpic,
              lyrcis: '', // 为空
              sourceId: row.sourceId,
              id: row.id, // 根据id获取歌曲链接和歌词
              time: new Date().getTime(),
              loved: false,
            })
            return this.showMessage('音乐添加成功')
          })
          break;
        default:
          break;
      }
    },

    // 歌曲链接失效警告
    checkMusicUrl (url) {
      return this.showMessage('歌曲链接失效，试试从其他的站点获取吧')
    },

    // 检查当前播放列表中是否已经有该歌曲
    checkMusicList (target) {
      return this.playList.find(v => {
        return v.title === target.title && v.artist === target.artist && v.id === target.id
      })
    },

    // 搜索按钮点击
    searchMusic () {
      this.searchListLoad = true
      switch (this.searchType) {
        case '0':
          this.getMusicFromKuGou()
          break;
        case '1':
          this.getMusicFromMiGu()
          break;
        case '2':
          this.getMusicFromQQ()
          break;
        case '3':
          this.getMusicFromNetease()
          break;
        case '4':
          this.getMusicFromKuWo()
          break;
        default:
          this.searchListLoad = false
          break;
      }
    },

    // 酷狗搜索
    getMusicFromKuGou () {
      if (this.searchKey.trim().length === 0) return

      searchFromKuGou(this.searchKey, this.page, this.pagesize).then(res => {
        if (res.status !== 200) {
          throw new Error('酷狗搜索失败')
        }
        // console.log(res.data)
        let data = res.data.map((v, i) => {
          return {
            number: i,
            title: v.SongName,
            artist: v.SingerName,
            src: '',
            hover: false,
            from: '酷狗音乐',
            sourceId: 0, // 酷狗音乐代码 0
            audition: v.trans_param.musicpack_advance ? 0 : 1,
            hash: v.FileHash,
            id: v.AlbumID
          }
        })
        if (this.page === 1) {
          this.musicList = data
        } else {
          this.musicList.push(...data)
        }
        // 避免第一页加载歌曲数目太少的问题
        if (this.musicList.length < this.pagesize) {
          this.$nextTick(() => {
            this.page++
          })
        }
        this.searchListLoad = false
      })
    },

    // 咪咕搜索
    getMusicFromMiGu () {
      if (this.searchKey.trim().length === 0) return
      searchFromMiGu(this.searchKey, this.page, this.pagesize).then(res => {
        if (res.status !== 200) {
          throw new Error('咪咕搜索失败')
        }
        // 搜索结果列表
        let data = res.data.map(v => {
          let singers = '', url = v.rateFormats[0].url, fileHead = 'http://freetyst.nf.migu.cn'
          for (let i of v.singers) {
            singers += i.name + '、'
          }
          // url2 = data[0].newRateFormats[0].url,
          return {
            // number: i,
            title: v.name,
            artist: singers.slice(0, singers.length - 1),
            src: url.replace(/ftp:\/\/\d+\.\d+\.\d+\.\d+:\d+/, fileHead),
            hover: false,
            from: '咪咕音乐',
            sourceId: 1, // 咪咕音乐代码 1
            audition: 1,
            img: v.imgItems[2].img,
            lyrics: '',
            id: v.copyrightId
          }
        })
        if (this.page === 1) {
          this.musicList = data
        } else {
          this.musicList.push(...data)
        }
        // 避免第一页加载歌曲数目太少的问题
        if (this.musicList.length < this.pagesize) {
          this.$nextTick(() => {
            this.page++
          })
        }
        this.searchListLoad = false
      })
    },

    // QQ搜索
    getMusicFromQQ () {
      if (this.searchKey.trim().length === 0) return
      searchFromQQ(this.searchKey, this.page, this.pagesize).then(res => {
        if (res.status !== 200) {
          throw new Error('QQ搜索失败')
        }
        // 搜索结果列表
        let data = res.data.map(v => {
          return {
            // number: i,
            title: v.songname,
            artist: v.singer.map(v => v.name).join('、'),
            src: "https://api88.net/api/qqmusic/?key=06763c2a6def5f30&type=url&id=" + v.songmid,
            hover: false,
            from: 'QQ音乐',
            sourceId: 2, // QQ音乐代码 2
            audition: '完整版',
            img: "https://api88.net/api/qqmusic/?key=06763c2a6def5f30&cache=&type=pic&id=" + v.songmid,
            lyrcis: "https://api88.net/api/qqmusic/?key=06763c2a6def5f30&cache=&type=lrc&id=" + v.songmid,
            id: v.songmid
          }
        })
        if (this.page === 1) {
          this.musicList = data
        } else {
          this.musicList.push(...data)
        }
        // 避免第一页加载歌曲数目太少的问题
        if (this.musicList.length < this.pagesize) {
          this.$nextTick(() => {
            this.page++
          })
        }
        this.searchListLoad = false
      })
    },

    // 网易云搜索
    getMusicFromNetease () {
      if (this.searchKey.trim().length === 0) return
      searchFromNetease(this.searchKey, this.page - 1, this.pagesize).then(res => {
        if (res.status !== 200) {
          throw new Error('网易云搜索错误')
        }
        // console.log(res.data)
        // let data = res.data.data.songs.map(v => { 第一个搜索接口每日限制100次
        let data = res.data.map(v => {
          return {
            title: v.name,
            artist: v.artists.map(v => v.name).join('、'),
            src: '',
            hover: false,
            from: '网易云音乐',
            sourceId: 3, // 网易云音乐代码 3
            audition: 1,
            img: v.album.artist.img1v1Url,
            lyrcis: '',
            id: v.id,
            albumid: v.album.id // 专辑id
          }
        })

        // console.log(data)
        if (this.page === 1) {
          this.musicList = data
        } else {
          this.musicList.push(...data)
        }
        // 避免第一页加载歌曲数目太少的问题
        if (this.musicList.length < this.pagesize) {
          this.$nextTick(() => {
            this.page++
          })
        }
        this.searchListLoad = false
      })
    },

    // 酷我搜索
    getMusicFromKuWo () {
      if (this.searchKey.trim().length === 0) return
      searchFromKuWo(this.searchKey, this.page, this.pagesize).then(res => {
        // console.log(res.data.data.music)
        let data = res.data.map(v => {
          return {
            title: v.name,
            artist: v.artist_name.replace(/&/g, '、'),
            src: '',
            hover: false,
            from: '酷我音乐',
            sourceId: 4, // 酷我音乐代码 4
            audition: 1,
            img: '',
            lyrcis: '',
            id: v.id
          }
        })
        // console.log(data)
        if (this.page === 1) {
          this.musicList = data
        } else {
          this.musicList.push(...data)
        }
        // 避免第一页加载歌曲数目太少的问题
        if (this.musicList.length < this.pagesize) {
          this.$nextTick(() => {
            this.page++
          })
        }
        this.searchListLoad = false
      })
    },

    // 加载更多
    loadMore () {
      this.page++
    },

    // 提示信息
    showMessage (text) {
      this.$message({
        dangerouslyUseHTMLString: true,
        center: true,
        duration: 1800,
        message: '<p style="color: #009a61;font-size: 15px;">' + text + '</p>',
      });
    },


  }
}
</script>

<style scoped lang="scss">
.search-list {
  // 搜索列表样式
  & >>> .el-table {
    width: 95%;
    margin-right: 20px;
    font-size: 12px;
    color: #cbcbcb;
    background: transparent;

    &::before {
      height: 0;
      background-color: transparent !important;
    }

    th,
    tr {
      font-weight: initial;
      background: transparent;
    }

    tr {
      transition: 0.3;
    }

    td {
      padding: 7px 0;
      border-top: 1px solid #eeeeee3f;
      border-bottom: none;
    }

    tr:hover > td {
      background: initial;
    }

    tr:hover {
      background: rgba(255, 255, 255, 0.034);
    }

    .cell {
      display: flex;
      justify-content: flex-start;
      align-items: center;

      // 试听
      img {
        height: 23px;
      }
    }

    // 操作按钮样式
    .btn {
      // color: #6d6d6d3d;
      color: #cbcbcb;
      font-size: 20px;
      margin-right: 3px;
      cursor: pointer;
      transition: 0.3s;

      &:hover {
        // color: rgb(0, 0, 0);
        color: #fff;
      }
    }

    .el-table__empty-text {
      color: #cbcbcb;
    }

    // 加载更多样式
    .load-more {
      // color: #909399;
      color: #cbcbcb;
      text-align: center;
      line-height: 30px;
      cursor: pointer;
      transition: 0.3s;

      &:hover {
        // color: #000;
        color: #fff;
      }
    }

    // loading
    .el-loading-mask {
      background: transparent;
    }
  }
}

// 手机端加载更多底边距问题
@media screen and (max-width: 600px) {
  .search-list {
    & >>> .el-table {
      .load-more {
        padding-bottom: 110px;
      }
    }
  }
}
</style>